package com.vr.xuecheng.learning.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vr.xuecheng.learning.dto.SaveOrUpdateLearnRecordDTO;
import com.vr.xuecheng.learning.entity.LearnRecord;
import com.vr.xuecheng.learning.mapper.LearnRecordMapper;
import com.vr.xuecheng.learning.service.ILearnRecordService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hzh
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class LearnRecordServiceImpl extends ServiceImpl<LearnRecordMapper, LearnRecord> implements ILearnRecordService {
    private final LearnRecordMapper learnRecordMapper;
    @Override
    public void updateOrSaveLearnRecord(SaveOrUpdateLearnRecordDTO params) {
        LearnRecord queryLearnRecord = learnRecordMapper.selectOne(
                new LambdaQueryWrapper<LearnRecord>()
                        .eq(LearnRecord::getUserId, params.getUserId())
                        .eq(LearnRecord::getCourseId, params.getCourseId())
                        .eq(LearnRecord::getTeachplanId, params.getTeachplanId()));
        if (queryLearnRecord==null) {
            LearnRecord learnRecord = LearnRecord.builder()
                    .courseId(params.getCourseId())
                    .courseName(params.getCourseName())
                    .userId(params.getUserId())
                    .learnDate(LocalDateTime.now())
                    .learnLength(0L)
                    .teachplanId(params.getTeachplanId())
                    .teachplanName(params.getTeachplanName())
                    .build();
            learnRecordMapper.insert(learnRecord);
        } else {
            LearnRecord learnRecord = BeanUtil.toBean(queryLearnRecord, LearnRecord.class);
            learnRecord.setLearnDate(LocalDateTime.now());
            learnRecordMapper.updateById(learnRecord);
        }
    }
}
